package com.huishao.demo.controller;


import com.huishao.demo.entity.DailyForm;
import com.huishao.demo.common.R;
import com.huishao.demo.common.PageResult;
import com.huishao.demo.entity.vo.DailyFormAndKey;
import com.huishao.demo.service.DailyFormService;
import com.huishao.demo.service.KeyService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;

import static com.huishao.demo.utils.IpUtil.getIpAddr;

/**
 * (DailyForm)表控制层
 *
 * @author huishao
 * @since 2023-02-17 13:55:40
 */
@Api(tags = "(dailyForm)", value = "(DailyForm)")
@RestController
@RequestMapping("/demo/dailyForm")
public class DailyFormController {
    /**
     * 服务对象
     */
    @Autowired
    private DailyFormService dailyFormService;

    @Autowired
    KeyService keyService;

    /**
     * 分页查询所有数据
     *
     * @param dailyForm 查询实体
     * @return 所有数据
     */
    @ApiOperation(value = "分页查询所有数据", notes = "")
    @GetMapping("/")
    public PageResult getAll(@RequestParam(defaultValue = "1") Integer currentPage,
                             @RequestParam(defaultValue = "10") Integer size,
                             DailyForm dailyForm) {
        return dailyFormService.getPage(currentPage, size, dailyForm);
    }


    /**
     * 新增数据
     *
     * @param dailyFormAndKey 实体对象并且携带Key
     * @return 新增结果
     */
    @ApiOperation(value = "新增数据 ")
    @PostMapping("/")
    public R<Object> insert(@RequestBody DailyFormAndKey dailyFormAndKey, HttpServletRequest httpServletRequest) {
        // 校验 key
        if (keyService.checkKey(dailyFormAndKey,httpServletRequest)){
            DailyForm dailyForm = new DailyForm();
            BeanUtils.copyProperties(dailyFormAndKey,dailyForm);
            dailyForm.setWriterFrom(getIpAddr(httpServletRequest));
            dailyFormService.save(dailyForm);
            return R.ok("添加成功");
        }
        return R.error("key校验失败！");

    }

    @ApiOperation(value = "通过id获取数据")
    @GetMapping("/getById/{id}")
    public R<Object> getById(@PathVariable String id) {
        if(dailyFormService.getById(id)!=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // DailyForm dailyForm = dailyFormService.getById(id);
            DailyFormAndKey dailyFormAndKey = new DailyFormAndKey();
            BeanUtils.copyProperties(dailyFormService.getById(id),dailyFormAndKey);
            dailyFormAndKey.setCreateTimeStr(simpleDateFormat.format(dailyFormService.getById(id).getCreateTime()));
            return R.success("获取成功！",dailyFormAndKey);
        }else {
            return R.error("未知异常，请上报管理员");
        }

    }


}

